extends IInventoryComponent


class_name InventoryEquipComponent
"""
负责挂载技能/装备,处理不同道具的使用逻辑
"""


## 拾取后是否自动使用
@export var is_auto_equip: bool = true

@export_category("Component")
## 挂载的角色
@export var character: ICharacterComponent = null
## 背包
@export var knapsack: InventoryComponent = null
## 挂载的道具
@export var equipment: InventoryComponent = null
@export_category("")


var __equip_map: Dictionary = {}


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "character": IComponent.find_up.bind(self, func(x): return x is ICharacterComponent, character),
        "knapsack": IComponent.find_child.bind(self, func(x): return x is InventoryComponent, knapsack),
        "equipment": func(): return equipment != null,
    }, super.__check_exports())

func __init_hooks() -> Dictionary:
    return IComponent.merge({
        knapsack.event_slot_triggered: on_knapsack_slot_trigger,
        equipment.event_slot_triggered: on_equipment_slot_trigger,
    }, super.__init_hooks())

func pickup(item: InventoryItem) -> bool:
    if is_auto_equip:
        item = equip(item)
        # 消耗完毕,不需要再放到knapsack中
        if item == null:
            return true
    return knapsack.pickup(item)

# 使用道具,返回剩余的Item
func equip(item: InventoryItem) -> InventoryItem:
    # 不可使用(如:材料)
    if item.source.usable == null:
        return item
    # 放置永久性道具
    if item.source.is_permanent:
        if not equipment.place(item):
            return item
    var usable: IUsableComponent = item.source.instantiate()
    NodeHelper.add_child(knapsack, usable)
    usable.apply(character.get_character())
    if item.source.is_permanent:
        __equip_map[item] = usable
        # 永久性道具,设置道具槽
        return null
    else:
        # 消耗性道具,减少道具数量
        item.amount -= 1
        usable.queue_free()
        if item.amount < 1:
            return null
    return item

func on_knapsack_slot_trigger(inventory: InventoryComponent, slot: InventorySlot) -> void:
    # 全部使用完
    if equip(slot.inventory_item) == null:
        slot.set_item(null)

func on_equipment_slot_trigger(inventory: InventoryComponent, slot: InventorySlot) -> void:
    var item: InventoryItem = slot.inventory_item
    var usable: IUsableComponent = __equip_map[item]
    __equip_map.erase(item)
    slot.set_item(null)
    usable.cancel()
    usable.queue_free()

    knapsack.pickup(item)
